<template>
  <base-container>
    <QueryFilter
      :model="queryFields"
      :label-col="{ style: { width: '70px' } }"
      @submit="loadActivityList"
      @reset="resetActivity"
    >
      <a-form-item name="type" label="活动类型">
        <a-select v-model:value="queryFields.type" placeholder="请选择活动类型" :options="activityTypeOptions" />
      </a-form-item>
      <a-form-item name="status" label="活动状态">
        <a-select v-model:value="queryFields.status" placeholder="请选择活动状态" :options="activityStatusOptions" />
      </a-form-item>
      <a-form-item name="startTime" label="活动时间">
        <a-range-picker v-model:value="dateRange" value-format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
    </QueryFilter>
    <Divider />
    <table-toolbar title="活动列表">
      <a-button type="primary" class="mr-2" @click="handleUpdateActivity(Mode.create)">
        <template #icon><plus-outlined /></template>
        新增活动
      </a-button>
    </table-toolbar>
    <a-table
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      :columns="columns"
      :data-source="activityList"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.key === 'status'">
          <a-badge :status="ActivityStatusColor[text]" :text="ActivityStatusKeyMap[text]" />
        </template>
        <template v-if="column.key === 'operate'">
          <a-button type="primary" @click="handleUpdateActivity(Mode.edit, record)">编辑</a-button>
          <a-button class="ml-2" @click="handleActivityDetail(record)">详情</a-button>
          <a-dropdown>
            <template #overlay>
              <a-menu @click="handleMenuClick(record, $event)">
                <template v-if="computedActivityExpired(record)">
                  <a-menu-item disabled>活动已过期</a-menu-item>
                </template>
                <template v-else-if="computedActivityNotStarted(record)">
                  <a-menu-item disabled>活动未开始</a-menu-item>
                </template>
                <template v-else>
                  <a-menu-item key="1" v-if="record.status === ActivityStatusEnum.Offline"> 上线 </a-menu-item>
                  <a-menu-item key="2" v-else> 下线 </a-menu-item>
                </template>
                <!--<a-menu-item key="3"> 删除 </a-menu-item>-->
              </a-menu>
            </template>
            <a-button class="ml-2">
              操作
              <DownOutlined />
            </a-button>
          </a-dropdown>
        </template>
      </template>
    </a-table>
    <activity-updater
      v-model:data="formFields"
      v-model:show="visible"
      :submitting="submitting"
      :loading="inquiring"
      :mode="mode"
      @on-submit="handleSubmit"
      @on-update-rule="handleActivityRule"
    />
  </base-container>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import BaseContainer from '@/components/base-container/index.vue'
import getActivityList from '@/services/activity/getActivityList'
import TableToolbar from '@/components/table-toolbar/index.vue'
import { DownOutlined, PlusOutlined } from '@ant-design/icons-vue'
import Divider from '@/components/divider/index.vue'
import QueryFilter from '@/components/query-filter/index.vue'
import { getUUid, toLabelValue } from '@/utils'
import updateActivityStatus from '@/services/activity/updateActivityStatus'
import removeActivity from '@/services/activity/removeActivity'
import ActivityUpdater from '@/views/activity/components/ActivityUpdater.vue'
import updateActivity, { type ActivityFields } from '@/services/activity/updateActivity'
import type { SetRequired } from 'type-fest'
import { message, Modal, type TableProps } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import getActivity from '@/services/activity/getActivity'
import dayjs from 'dayjs'
import type { Activity } from '@/core/interfaces/activity'
import { ActivityStatusEnum } from '@/core/enums/status'
import { ActivityTypeEnum } from '@/core/enums/type'
import { ActivityTypeKeyMap } from '@/core/mapper/activity'
import { ActivityStatusColor, ActivityStatusKeyMap } from '@/core/mapper/status'
import { Mode } from '@/core/interfaces/common'
import { ComboPriceNameEnum } from '@/core/enums/name'

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

const defaultQueryFields = () => ({
  status: ActivityStatusEnum.All,
  type: ActivityTypeEnum.All,
  startTime: '',
  endTime: ''
})

const defaultFormFields = () => ({
  startTime: '',
  endTime: '',
  type: ActivityTypeEnum.Word,
  status: ActivityStatusEnum.Offline,
  highestHeat: undefined,
  freeWordRules: [
    {
      lowPrice: undefined,
      highPrice: undefined,
      wordNum: undefined,
      combinedWordNum: undefined,
      activityId: undefined,
      pcImgNum: undefined,
      ydImgNum: undefined
    }
  ],
  daysType: ComboPriceNameEnum.YEAR,
  daysbanben: ComboPriceNameEnum.BAXIN
})

const router = useRouter()
const queryFields = reactive(defaultQueryFields())
const activityTypeOptions = toLabelValue(ActivityTypeKeyMap)
const activityStatusOptions = toLabelValue(ActivityStatusKeyMap)
const formFields = ref<ActivityFields>(defaultFormFields())
const visible = ref(false)
const mode = ref<Mode>(Mode.create)
const [activityList, fetchActivityList, loading] = getActivityList()
const [, fetchActivity, inquiring] = getActivity()
const [, fetchActivityStatus] = updateActivityStatus()
const [, fetchUpdateActivity, submitting] = updateActivity()
const [, deleteActivity] = removeActivity()

const dateRange = computed({
  set(val: string[]) {
    if (val) {
      const [startTime, endTime] = val
      queryFields.startTime = startTime
      queryFields.endTime = endTime
    } else {
      queryFields.startTime = ''
      queryFields.endTime = ''
    }
  },
  get() {
    if (queryFields.startTime && queryFields.endTime) {
      return [queryFields.startTime, queryFields.endTime]
    } else {
      return []
    }
  }
})

const columns: TableProps['columns'] = [
  {
    title: '活动id',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '活动类型',
    dataIndex: 'type',
    key: 'type',
    customRender: ({ text }: { text: ActivityTypeEnum }) => {
      return ActivityTypeKeyMap[text]
    }
  },

  {
    title: '版本',
    dataIndex: 'productType',
    key: 'productType',
    customRender: ({ text }) => {
      return text || '---'
    }
  },

  {
    title: '推广时长',
    dataIndex: 'daysType',
    key: 'daysType',
    customRender: ({ text }) => {
      return text || '---'
    }
  },
  {
    title: '活动状态',
    dataIndex: 'status',
    key: 'status',
    customRender: ({ text }: { text: ActivityStatusEnum }) => {
      return ActivityStatusKeyMap[text]
    }
  },
  {
    title: '活动开始时间',
    dataIndex: 'startTime',
    key: 'startTime'
  },
  {
    title: '活动结束时间',
    dataIndex: 'endTime',
    key: 'endTime'
  },
  {
    title: '操作',
    dataIndex: 'operate',
    key: 'operate',
    width: '245px'
  }
]

async function loadActivityList() {
  const [err, res] = await fetchActivityList({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    status: queryFields.status,
    type: queryFields.type,
    startTime: queryFields.startTime,
    endTime: queryFields.endTime
  })

  if (!err) {
    pagination.total = res.data.data.totalSize
  }
}

function resetActivity() {
  Object.assign(queryFields, defaultQueryFields())
}

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadActivityList()
}

function computedActivityExpired(record: Activity) {
  return dayjs().isAfter(dayjs(record.endTime))
}

function computedActivityNotStarted(record: Activity) {
  return dayjs().isBefore(dayjs(record.startTime))
}

function handleMenuClick(record: SetRequired<Activity, 'id'>, { key }: { key: string }) {
  switch (key) {
    case '1':
      return handleOnline(record)
    case '2':
      return handleOffline(record)
    case '3':
      return handleDelete(record)
  }
}

function handleOnline(record: SetRequired<Activity, 'id'>) {
  Modal.confirm({
    title: '提示',
    content: '确定更改为上线吗？',
    async onOk() {
      const [err, res] = await fetchActivityStatus({ activityId: record.id }, ActivityStatusEnum.Online)

      if (!err) {
        message.success(res.data.msg || '修改成功')
        await loadActivityList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handleOffline(record: SetRequired<Activity, 'id'>) {
  Modal.confirm({
    title: '提示',
    content: '确定更改为下线吗？',
    async onOk() {
      const [err, res] = await fetchActivityStatus({ activityId: record.id }, ActivityStatusEnum.Offline)

      if (!err) {
        message.success(res.data.msg || '修改成功')
        await loadActivityList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handleDelete(record: SetRequired<Activity, 'id'>) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗？',
    async onOk() {
      const [err, res] = await deleteActivity({ activityId: record.id })

      if (!err) {
        message.success(res.data.msg || '删除成功')
        await loadActivityList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handleSubmit() {
  Modal.confirm({
    title: '提示',
    content: '确定要提交活动规则吗？',
    async onOk() {
      const [err, res] = await fetchUpdateActivity(formFields.value, mode.value)

      if (!err) {
        visible.value = false
        message.success(res.data.msg || '添加成功')
        pagination.current = 1
        await loadActivityList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handleActivityRule() {
  formFields.value.freeWordRules.push({
    key: getUUid(),
    lowPrice: undefined,
    highPrice: undefined,
    wordNum: undefined,
    combinedWordNum: undefined,
    activityId: formFields.value.id
  })
}

async function handleUpdateActivity(m: Mode, record?: Activity) {
  formFields.value = defaultFormFields()
  mode.value = m
  visible.value = true

  if (m === Mode.edit) {
    const [err, res] = await fetchActivity({
      activityId: record!.id!
    })

    if (!err) {
      formFields.value = res.data.data
    }
  }
}

function handleActivityDetail(record: Activity) {
  router.push({
    name: 'activity-detail',
    query: {
      id: record.id
    }
  })
}

onMounted(() => {
  loadActivityList()
})
</script>

<script lang="ts">
export default {
  name: 'ActivityManager'
}
</script>
